import socket
import time
import network
import machine

# esp32 目前不支持5G 路由器 可用手机开热点进行测试
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.config(ssid='ESP888') # set the SSID of the access point
ap.config(max_clients=10) # set how many clients can connect to the network
# ap.config(authmode=3,password='1234567890',hidden=True) 设置隐藏wifi
ap.active(True)         # activate the interface
ip = ap.ifconfig()
print(ip)
print(ap.isconnected())

def start_udp():
    # 2. 启动网络功能（UDP）

    # 2.1. 创建udp套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 2.2. 绑定本地信息 0.0.0.0 也
    udp_socket.bind(("192.168.4.1", 7788))

    return udp_socket

def main():
    # 2. 创建UDP
    udp_socket = start_udp()
    # 3. 创建灯对象
    led = machine.Pin(12, machine.Pin.OUT)
    led3 = machine.Pin(13, machine.Pin.OUT)
    
    led3.value(1)
    
    print("333")
    
    while True:
        led.value(1)
        # 2. 准备接收方的地址
        dest_addr = ('192.168.4.4', 7788)
        # 3. 从键盘获取数据
        send_data = "light on"
        # 4. 发送数据到指定的电脑上
        udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
        time.sleep(2)
        led.value(0)
        # 2. 准备接收方的地址
        dest_addr = ('192.168.4.4', 7788)
        # 3. 从键盘获取数据
        send_data = "light off"
        # 4. 发送数据到指定的电脑上
        udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
        time.sleep(2)
    
    # 4. 接收网络数据
    while True:
        recv_data, sender_info = udp_socket.recvfrom(1024)
        print("{}发送{}".format(sender_info, recv_data))
        recv_data_str = recv_data.decode("utf-8")
        try:
            print(recv_data_str)
        except Exception as ret:
            print("error:", ret)
        
        # 5. 处理接收的数据
        if recv_data_str == "light on":
            print("这里是要灯亮的代码...")
            led.value(1)
            time.sleep(1)
            
            # 2. 准备接收方的地址
            dest_addr = ('192.168.4.4', 7788)
            # 3. 从键盘获取数据
            send_data = "light on"
            # 4. 发送数据到指定的电脑上
            udp_socket.sendto(send_data.encode('utf-8'), dest_addr)
        elif recv_data_str == "light off":
            print("这里是要灯灭的代码...")
            led.value(0)


if __name__ == "__main__":
    main()

